/**
 * @file 后台接口文件
 *
 * @author fanxingguang
 * 2016-10-31
 */
'use strict';
const _ = require('lodash');
const modelArticle = require('../../models/article');
const DATA = {
    msg: '',
    code: 0,
    data: ''
};
const spider = require('../common/spider');

/**
 * [获取翻页数据]
 *
 * @param  {Object} req   [req对象]
 * @param  {Object} res   [res对象]
 * @param  {Object} param [过滤条件]
 */
const getArticlesWithPage = (req, res, param) => {
    let currentPage = +req.query.currentPage;
    let pageSize = +req.query.pageSize;
    let data = _.clone(DATA);
    let pArticles = new Promise(resolve => {
        modelArticle
            .find(param)
            .skip((currentPage - 1) * pageSize)
            .limit(pageSize)
            .exec((err, result) => {
                if (err) {
                    throw err;
                }
                resolve(result);
            });
    });
    let pTotal = new Promise(resolve => {
        modelArticle.find({}).count((err, result) => {
            if (err) {
                throw err;
            }
            resolve(result);
        });
    });
    Promise.all([pArticles, pTotal]).then(vals => {
        data.data = {
            data: vals[0],
            total: vals[1]
        };
        res.json(data);
    });
};

module.exports = {
    get: {
        getArticleById(req, res) {
            let data = _.clone(DATA);
            let id = req.query.id;
            modelArticle.findById(id, (err, result) => {
                data.data = result;
                res.json(data);
            });
        },
        getAllArticles(req, res) {
            getArticlesWithPage(req, res, {});
        },
        getArticlesByColumnId(req, res) {
            getArticlesWithPage(req, res, {columnId: req.query.columnId});
        },
        drawArticlesBySpider(req, res) {
            // 是否返回，是否保存
            // let {isReturn, isSave} = req.query;
            let data = _.clone(DATA);
            spider({
                listUrl: 'http://fex.baidu.com/articles/',
                listSelector: '.articles .post-list li > a',
                page: [{
                    key: 'title',
                    selector: '.article-info .title',
                    type: 'text'
                }, {
                    key: 'author',
                    selector: '.article-info .author',
                    type: 'text'
                }, {
                    key: 'content',
                    selector: '.content',
                    type: 'html'
                }]
            }).then(result => {
                result.forEach(entity => {
                    entity.createDate = new Date();
                    entity.updateDate = new Date();
                    modelArticle.create(entity, err => {
                        if (err) {
                            data.code = 1;
                            data.msg = err + '';
                            res.json(data);
                        }
                    });
                });
                res.json(result);
            });
        }
    },
    post: {
        addArticle(req, res) {
            let data = _.clone(DATA);
            let entity = req.body;
            entity.createDate = new Date();
            entity.updateDate = new Date();
            modelArticle.create(entity, err => {
                if (err) {
                    data.code = 1;
                    data.msg = err + '';
                }
                res.json(data);
            });
        },
        updateArticle(req, res) {
            let data = _.clone(DATA);
            let id = req.body._id;
            let newColumn = _.cloneDeep(req.body);
            delete newColumn._id;
            modelArticle.findByIdAndUpdate(id, {$set: newColumn}, err => {
                if (err) {
                    data.code = 1;
                    data.msg = err + '';
                }
                res.json(data);
            });
        },
        deleteArticleById(req, res) {
            let data = _.clone(DATA);
            let id = req.body.id;
            modelArticle.findByIdAndRemove(id, err => {
                if (err) {
                    data.code = 1;
                    data.msg = err + '';
                }
                res.json(data);
            });
        }
    }
};
